package com.example.timetable;

import androidx.annotation.NonNull;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;


import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.view.MenuItem;

import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;


import com.alibaba.android.arouter.facade.annotation.Route;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;
import butterknife.OnItemSelected;
import butterknife.OnLongClick;

@Route(path="/TimeTable/CountDowm")
public class CountDown extends AppCompatActivity {

    @BindView(R.id.list_view_count_dowm)
    ListView listView;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    AlertDialog.Builder builder;
    Map<String,String> map;
    ArrayList<Map<String,Object>> arrayList;
    SimpleAdapter simpleAdapter;
    int deletekey=-1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_down);
        ButterKnife.bind(this);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        preferences=getSharedPreferences("CountDowm", MODE_PRIVATE);
        editor=preferences.edit();
        showListView();
    }
    @OnClick(R.id.add_count_dowm)
    public void onClickCountDowm(){
        initDialog();
        builder.show();
    }
    public void initDialog(){
        builder=new AlertDialog.Builder(this);
        builder.setTitle("增加科目");
        LinearLayout linearLayout=new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        EditText editText=new EditText(this);
        editText.setHint("科目名称");
        CalendarView calendarView=new CalendarView(this);
        linearLayout.addView(editText);
        linearLayout.addView(calendarView);
        builder.setView(linearLayout);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date=new Date(calendarView.getDate());
        String ymd []=new String[1];
        ymd[0]=simpleDateFormat.format(date);
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                ymd[0]=year+"-"+(month+1)+"-"+dayOfMonth;
                try {
                    Date date1=simpleDateFormat.parse(ymd[0]);
                    ymd[0]=simpleDateFormat.format(date1);
                }catch (Exception e){
                    System.out.println(e);
                }
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(deletekey!=-1){
                    deleteItem(deletekey);
                    deletekey=-1;
                }
                String name=editText.getText().toString();
                editor.putString(name,ymd[0]);
                editor.commit();
                showListView();
            }
        });
    }
    protected void showListView(){
        arrayList=new ArrayList<>();
        //获取数据
        map = (Map<String,String>) preferences.getAll();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map<String, Object> data = new HashMap<>();
            Map.Entry<String, String> entry = it.next();
            Date date1,date2;
            int days=0;
            try{
                date1=simpleDateFormat.parse(entry.getValue()); //选择的时间
                String temp=simpleDateFormat.format(new Date()); //当前时间（去掉时分秒）
                date2=simpleDateFormat.parse(temp);
                //计算相隔天数
                days = (int) (date1.getTime()-date2.getTime()+1000000)/(60*60*24*1000);
                days=days<=0?0:days;
            }catch (Exception e){

            }
            data.put("text1",days);
            data.put("text2", entry.getKey());
            data.put("text3", entry.getValue());
            arrayList.add(data);
        }
        simpleAdapter = new SimpleAdapter(this, arrayList, R.layout.list_view_item2, new String[]{"text1", "text2","text3"}, new int[]{R.id.text1, R.id.text2,R.id.text3});
        listView.setAdapter(simpleAdapter);
    }
    @OnItemLongClick(R.id.list_view_count_dowm)
    public void onClickLSCountDowm(int position){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        AlertDialog alertDialog=builder.create();
        builder.setTitle("是否删除？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteItem(position);
                showListView();
            }
        });
        builder.setNegativeButton("返回",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        builder.show();
    }
    protected void deleteItem(int position){
        Map<String,Object> item=arrayList.get(position);
        editor.remove((String)item.get("text2"));
        editor.commit();
    }
    @OnItemClick(R.id.list_view_count_dowm)
    public void onItemClickLSCountDowm(int position){
        deletekey=position;
        initDialog();
        builder.show();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
